#include "distinguish.h"
#include "ui_distinguish.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include<QSqlError>
#include <QMessageBox>
#include <QDebug>
#include <QDateTime>

#include <QCameraInfo>
#include <QFileDialog>
#include <QPixmap>
#include "widget.h"

distinguish::distinguish(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::distinguish), camera(nullptr), viewfinder(nullptr), capture(nullptr)
{
    ui->setupUi(this);

    QSqlDatabase db;
       if (QSqlDatabase::contains("qt_sql_default_connection")) {
           db = QSqlDatabase::database("qt_sql_default_connection");
       } else {
           db = QSqlDatabase::addDatabase("QMYSQL", "qt_sql_default_connection");
           db.setHostName("43.141.197.129");
           db.setPort(29843);
           db.setDatabaseName("face");
           db.setUserName("mao");
           db.setPassword("Mjh842603317");

           if (!db.open()) {
               qDebug() << "MySQL数据库打开失败" << db.lastError().text();
           } else {
               qDebug() << "MySQL数据库连接成功";
           }
       }

    // 摄像头初始化（来自 zhao 分支）
    ui->lb_showface->setScaledContents(true);
    ui->button_close->setEnabled(false);
    ui->button_takeph->setEnabled(false);
}

distinguish::~distinguish()
{
    delete ui;
    delete camera;
    delete viewfinder;
    delete capture;
}

// 开启摄像头（来自 zhao 分支）
void distinguish::on_button_open_clicked()
{
    QList<QCameraInfo> cameras = QCameraInfo::availableCameras();
    if (cameras.count() > 0) {
        camera = new QCamera(cameras.at(0), this);
    }

    viewfinder = new QCameraViewfinder(this);
    viewfinder->resize(ui->lb_cam->size());
    viewfinder->setParent(ui->lb_cam);

    camera->setCaptureMode(QCamera::CaptureVideo);
    camera->setViewfinder(viewfinder);
    viewfinder->show();
    camera->start();

    ui->button_open->setEnabled(false);
    ui->button_close->setEnabled(true);
    ui->button_takeph->setEnabled(true);

    adjustViewfinderSize();
}

// 调整摄像头显示窗口大小
void distinguish::adjustViewfinderSize()
{
    if (viewfinder && ui->lb_cam->layout()) {
        viewfinder->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        viewfinder->setMinimumSize(ui->lb_cam->size());
        viewfinder->resize(ui->lb_cam->size());
    }
}

// 拍摄照片（来自 zhao 分支）
void distinguish::on_button_takeph_clicked()
{
    capture = new QCameraImageCapture(camera);
    this->fileName = QFileDialog::getSaveFileName();
    camera->setCaptureMode(QCamera::CaptureStillImage);
    camera->searchAndLock();
    capture->capture(fileName);
    camera->searchAndLock();

    connect(capture, &QCameraImageCapture::imageCaptured, this, [this](int id, const QImage &preview) {
        QPixmap pix = QPixmap::fromImage(preview);
        pix = pix.scaled(ui->lb_showface->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
        ui->lb_showface->setPixmap(pix);
    });

    ui->lb_cam->clear();
    camera->searchAndLock();
}

// 关闭摄像头（来自 zhao 分支）
void distinguish::on_button_close_clicked()
{
    if (camera) {
        camera->stop();
    }
    if (viewfinder) {
        viewfinder->hide();
    }

    ui->lb_showface->setPixmap(QPixmap());
    ui->button_open->setEnabled(true);
    ui->button_close->setEnabled(false);
    ui->button_takeph->setEnabled(false);
}

// 数据保存逻辑（来自 HEAD 分支）
void distinguish::on_pushButton_clicked()
{
    QString name = ui->le_name->text();
    QString gender;
    if (ui->radioButton->isChecked()) {
        gender = "男";
    } else if (ui->radioButton_2->isChecked()) {
        gender = "女";
    } else {
        QMessageBox::warning(this, "输入错误", "请选择性别！");
        return;
    }

    QString department = ui->le_department->text();
    QString employee_id = ui->le_worknum->text();

    if (name.isEmpty() || department.isEmpty() || employee_id.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "请填写所有必填项！");
        return;
    }

    QDateTime currentTime = QDateTime::currentDateTime();
    QString registTime = currentTime.toString("yyyy-MM-dd HH:mm:ss");
    QString pic_path = this->fileName;

    QSqlQuery query;
    QString queryStr = "INSERT INTO emp (name, gender, depart, wid, regist, picpath) VALUES (?, ?, ?, ?, ?, ?)";//"INSERT INTO emp VALUES(?,?,?,?,?,?)";
    query.prepare(queryStr);
    query.addBindValue(name);
    query.addBindValue(gender);
    query.addBindValue(department);
    query.addBindValue(employee_id);
    query.addBindValue(registTime);
    query.addBindValue(pic_path);


     Widget obj;
     obj.registerFace(obj.accessToken,pic_path,employee_id,"22",name);


    if (!query.exec()) {
        qDebug() << "插入数据失败：" << query.lastError().text();
    }

    QMessageBox::information(this, "保存成功", "数据已成功保存！");
    ui->le_name->clear();
    ui->radioButton->setChecked(false);
    ui->radioButton_2->setChecked(false);
    ui->le_department->clear();
    ui->le_worknum->clear();
}
